/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    Text,
    useTheme,
    Container,
    Button,
    IconArrowRight,
    Input,
    Select,
    CheckSwitch,
    LineColumn,
    SuffixInput, InputLine, ComboBoxDatalist, InputDatalist,
    CommitInput, TextArea, ButtonRefComp, IconButton, IconZapOff, IconCheckSquare
} from "customize-easy-ui-component";
//import { DialogEnterReturn } from "../../context/DialogEnterReturn";
//import queryString from "querystring";
// import {useCommnBaseParm, CommnBase} from "./CommnBase";
import {useContext, useRef} from "react";
import {ChooseEqps} from "../../comp/ChooseEqps";
import useFlowToMutation from "../hook/useFlowRequestMutation";
import {OneUserChoose} from "../../common/user/OneUserChoose";
import RoutingContext from "../../routing/RoutingContext";
import {使用状态s} from "../../pipeline/edit/管道单元";
import UserContext from "../../routing/UserContext";
import {ChooseUnit} from "../../unit/ChooseUnit";
import useClipboard from "react-use-clipboard";
// import HashLinkObserver from "react-hash-link";

// export const 设备单位关联类型s=[['useu','使用单位'],['owner','产权单位'],['mtu','维保单位']];

interface Props {
  // id?: string;
  readOnly?: boolean;
  editable?: boolean;
  //当前申请单数据
  req?:any;
  //去修改设备数据
  //setEqp:  React.Dispatch<React.SetStateAction<any>>;
  //graphQL的变更执行回调函数 (...args: any[]) => any
  mutationFunc: (...args: any[]) => any;
    //当前待办流转单
    curFlow?:any;
}
/** 申请报告书修订申请单。修订许可 和 执行修改俩个分开申请的，前后关联。
 * */
export const RevisionPermit: React.FunctionComponent<Props> = (
    {
       readOnly,
       editable,
       req=null,    //【只读的】:从好几代祖先前的DetailedGuide在graphQL获得后端服务器数据层层传递下来的。
      mutationFunc,
        curFlow,
     }) =>
{
  //这个位置就应该体现解析graphQL内省的json集合字段：data:{}从string变身对象。
  const theme = useTheme();
    const { history } = useContext(RoutingContext);
  const {save, field, reurl}= window.history.state?.state??{};      //通用伪对话框传递格式:多选设备返回对象
    //假如从多选选定设备页面返回的："移出多选集" : "加入多选集" 操作过后，将会导致save.devs[]对象变身成了设备页面的经过SessionStorage倒腾一手的对象。
  const edt = save?  save : req;
  //若从save恢复的，confirm已经解析为对象Object:
  const  dat = edt?.dat instanceof Object?  edt?.dat : JSON.parse(edt?.dat || '{}');
  const [理由, set理由] = React.useState(dat?.理由);
    const [repNO, setRepNO] = React.useState(dat?.repNO);
    const [rpURL, setRpURL] = React.useState(dat?.rpURL);
  //【琢磨】仅仅存在于短期流程活动使用的需要结构化吗？成本和收益对比？,本来应当是关联对象的却被非结构化，graphQL没办法内省的，片段快照某些关键字段？？
    //非结构化关联对象的和正常JPA关联对象的优缺点对照： 前者适合于频繁新增删除的，关系生存时间短暂的，后端基本不参与计算的。
    //因为ChooseEqps对话框选择设备之后返回的实际数据字段通常是save.devs而不是我这非结构化json存储到了dat:{devs{[]}}，所以需要转换 #前提条件save?.devs表示挑选设备列表伪对话框之后调回来的。
    const [devs, setDevs] = React.useState(save?.devs? save.devs : dat?.devs);
    // const [unitZd, setUnitZd] = React.useState(dat?.unitZd || 'useu');
    //因为servu为对方框原本预计并非是在dat{servu:{}}这个结构里面的# 只好这样转换了 save? save.devs : 多个为对话框的混淆逻辑问题 【预设不应该有dat{}非结构化】
    //注意@前提：假定save.servu必须时选择了单位从伪对话框返回的。
    // const [servu, setServu] = React.useState(save?.servu? save.servu : dat?.servu);
    const [ust, setUst] = React.useState(dat?.ust);

  async function confirmation() {
    //前面垫底加了newdat={ ...req,  导致；id字段在XxxInput并没有定义，报错！输入和输出模型不能交换。
    const newdat={
      dat: {
          理由, repNO, rpURL
        },
    };
    //伪对话框跳转恢复也会用到的。
    return newdat;
  }
  //console.log("ChooseUnit跑来8history=",history, "location==",history.location);
/* const mountedRef = useRef(false);
  if(!mountedRef.current) {
    console.log("电梯Z组件当前id=",id,"未初始化￥=",mountedRef.current);
    mountedRef.current = true;
  }
  else   console.log("电梯Z组件当前id=",id,"已经初始化了=",mountedRef.current);*/

  // console.log("电梯组件传递x参数来svp Nowneqp=",req, "save=",save, cbp);
  //   const curFlow=sessionStorage['审批单']&&JSON.parse(sessionStorage['审批单']);
    const {call:flowToFunc,doing:flowing, called:flowed, reset:flowreset}=useFlowToMutation();
    //流转可能遇见两个人物：auditor审核人 或者 dispatcher最终责任人
    const [auditor, setAuditor] = React.useState<any>(req?.auditor);
    const [director, setDirector] = React.useState<any>(req?.director);
    const [manager, setManager] = React.useState<any>(req?.manager);
    const {user} = useContext(UserContext);
    const  audat = JSON.parse(edt?.audat || '{}');
    const [memo, setMemo] = React.useState<string|undefined>(audat?.memo);
    const  drdat = JSON.parse(edt?.drdat || '{}');
    const [drmemo, setDrmemo] = React.useState<string|undefined>(drdat?.memo);
    const  mndat = JSON.parse(edt?.mndat || '{}');
    const [mnmemo, setMnmemo] = React.useState<string|undefined>(mndat?.memo);
    const floUrl='/request/'+ req?.id;
    const commitBlurRef =React.useRef(null);
    const [isCopied, setCopied] = useClipboard(floUrl);    //其它申请单关联了本申请单地情况。

  return (
    <div
      css={{
        [theme.mediaQueries.md]: {
          height: "auto",
          display: "block"
        }
      }}
    >
      <Text
        css={{
          flex: 1,
          textAlign: "center",
          [theme.mediaQueries.md]: {
            textAlign: "left"
          }
        }}
        wrap={true}
        variant="h5"
        gutter={false}
      >
        原报告审核人、原报告批准人、技质部审批一共3关审批
      </Text>

      <div
        css={{
          flex: 1,
          [theme.mediaQueries.md]: {
            flex: "none"
          }
        }}
      >
        <div>
          <Container>
            <div
              css={{
                paddingTop: theme.spaces.lg,
                paddingBottom: theme.spaces.lg
              }}
            >
                <Text variant="h6">第一步，提交材料:</Text>
                <LineColumn >

                  <InputLine label={`本检验机构报告号:`}>
                    <CommitInput  value={ repNO || ''}  onSave={txt => setRepNO( txt || undefined) } />
                  </InputLine>
                    <InputLine label={`原报告书URL:`}>
                        <CommitInput  value={ rpURL || ''}  onSave={txt => setRpURL( txt || undefined) } />
                    </InputLine>
                    <InputLine label={`理由(具体修改细节):`}>
                        <TextArea required rows={8}
                                  value={理由} onChange={e => set理由( e.currentTarget.value||undefined ) }
                        />
                    </InputLine>

                 </LineColumn>

                {
                    (req?.status==='INIT') &&
                      <Button size="lg" intent="primary"  iconAfter={<IconArrowRight />}
                              css={{ marginTop: theme.spaces.sm, whiteSpace:'unset' }}
                              disabled={req?.status !== 'INIT'}
                        onPress={ async () => {
                          const sendInp=await confirmation();
                          const inpPreare={ ...sendInp,
                              dat: JSON.stringify({...sendInp.dat}),
                          };
                          await mutationFunc(req?.id, 'UPD', inpPreare);
                        } }
                      > 先保存申请资料
                      </Button>
                }
            </div>

              <InputLine label='原报告审核人(点进选择):'>
                  <OneUserChoose name={director?.person?.name!} setEditorVar={setDirector}
                                 oobj={director}/>
              </InputLine>
              { (req?.status==='INIT' || (curFlow && curFlow?.entId === req?.id && curFlow?.tdId==='request_author_modify') ) &&
                  <Button intent="primary" disabled={(curFlow && !(curFlow?.entId === req?.id) && req?.status!=='INIT') || !director}
                          onPress={async () => {
                              // const opndat= req?.status==='INIT' ? '' :
                              //     JSON.stringify({memo,});
                              await flowToFunc(curFlow?.utId, req?.id,1,"", "YES","申请报告书修订:"+user?.person?.name,
                                  director?.id, floUrl, 40);
                              sessionStorage['审批单'] = null;
                              history.push(`/zeebeTodo`);
                          }}
                  >
                      { ((curFlow?.tdId==='request_author_modify')? '再提交申请' : '提交申请给审核人') }
                  </Button>
              }

              <Text variant="h6">第二步，原报告审核人审核情况：</Text>
              {  ((curFlow && curFlow?.entId === req?.id) || req?.status!=='INIT') &&
                  <InputLine label={`审核人的意见:`}>
                      <CommitInput  value={ drmemo || ''}  onSave={txt => setDrmemo( txt || undefined) }
                                    placeholder="如果拒绝或回退的，请给出理由"
                      />
                  </InputLine>
              }
              <InputLine label='原报告批准人(点进选择):'>
                  <OneUserChoose name={manager?.person?.name!} setEditorVar={setManager}
                                 oobj={manager}/>
              </InputLine>

              { (curFlow?.entId === req?.id && curFlow?.tdId==='request_director_opinion') &&
                  <>
                  <ButtonRefComp intent="primary" disabled={(curFlow && !(curFlow?.entId === req?.id)) || !manager}
                                 ref={commitBlurRef}  onPointerOver={(e :any) => { // @ts-ignore
                                  commitBlurRef!.current!.focus(); }}
                          onPress={async () => {
                              //<CommitInput 地输入可能来不及收集触发： onBlur? onEnter()导致了 opndat为空parse JSON: unable to decode JSON: EOF
                              const opndat= req?.status==='INIT' ? '' :
                                                JSON.stringify({memo:drmemo,});
                              await flowToFunc(curFlow?.utId, req?.id,1,opndat, "YES","申请报告书修订:"+user?.person?.name,
                                  manager?.id, null, 20);
                              sessionStorage['审批单'] = null;     //后端这时流程节点可能已运行到了下一个节点了。
                              history.push(`/zeebeTodo`);
                          }}
                  >
                      {'通过的流转下步给批准人'}
                  </ButtonRefComp>
                  {
                      (req?.status!=='INIT') &&
                      <>
                          <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                  disabled={curFlow && !(curFlow?.entId === req?.id)}
                                  onPress={async () => {
                                      const opndat=JSON.stringify({memo:drmemo,});
                                      await flowToFunc(curFlow?.utId, req?.id,1,opndat, "NO","申请报告书修订:"+user?.person?.name,
                                          auditor?.id, null, 30);
                                      sessionStorage['审批单'] = null;
                                      history.push(`/zeebeTodo`);
                                  }}
                          >
                              { '审批不通过' }
                          </Button>
                          <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                  disabled={curFlow && !(curFlow?.entId === req?.id)}
                                  onPress={async () => {
                                      const opndat=JSON.stringify({memo:drmemo,});
                                      await flowToFunc(curFlow?.utId, req?.id,1,opndat, "BACK","申请报告书修订:"+user?.person?.name,
                                          auditor?.id, null, 30);
                                      sessionStorage['审批单'] = null;
                                      history.push(`/zeebeTodo`);
                                  }}
                          >
                              { '退回' }
                          </Button>
                      </>
                  }
               </>
            }
            

              <Text variant="h6">第三步，原报告批准人批准情况：</Text>
              {  ((curFlow && curFlow?.entId === req?.id) || req?.status!=='INIT') &&
                  <InputLine label={`批准人批准意见:`}>
                      <CommitInput  value={ mnmemo || ''}  onSave={txt => setMnmemo( txt || undefined) }
                                    placeholder="如果拒绝或回退的，请给出理由"
                      />
                  </InputLine>
              }

              <InputLine label='技质部审批人(点进选择):'>
                  <OneUserChoose name={auditor?.person?.name!} setEditorVar={setAuditor}
                                 oobj={auditor}/>
              </InputLine>
              { (curFlow?.entId === req?.id && curFlow?.tdId==='request_manager_opinion') &&
                  <>
                      <Button intent="primary" disabled={curFlow && !(curFlow?.entId === req?.id)}
                              onPress={async () => {
                                  const opndat= req?.status==='INIT' ? '' :
                                      JSON.stringify({memo:mnmemo,});

                                  await flowToFunc(curFlow?.utId, req?.id,2,opndat, "YES","申请报告书修订:"+user?.person?.name,
                                      auditor?.id, null, 40);
                                  sessionStorage['审批单'] = null;
                                  history.push(`/zeebeTodo`);
                              }}
                      >
                          { '通过的流转给技质部审批' }
                      </Button>
                      {
                          (req?.status!=='INIT') &&
                          <>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify({memo:mnmemo,});
                                          await flowToFunc(curFlow?.utId, req?.id,2,opndat, "NO","申请报告书修订:"+user?.person?.name,
                                              auditor?.id, null, 30);
                                          // toast({title: "流转前进一步"});
                                          //签字成功与否，都将可直接清空session状态; 不支持并发进行多个审批单子或多份报告同时进入审核工作范围。一个时间点只能一条审批事项。
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);     //实际并不会等待后端的响应的，直接跳转URL的。# await flowToFunc并不会阻塞到应答
                                      }}
                              >
                                  { '审批不通过' }
                              </Button>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify({memo:mnmemo,});
                                          await flowToFunc(curFlow?.utId, req?.id,2,opndat, "BACK","申请报告书修订:"+user?.person?.name,
                                              auditor?.id, null, 30);
                                          //为何点一次：后端跑了2回？？ 而且接口没保存memo?
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);     //实际并不会等待后端的响应的，直接跳转URL的。# await flowToFunc并不会阻塞到应答
                                      }}
                              >
                                  { '退回' }
                              </Button>
                          </>
                      }
                  </>
              }

              <Text variant="h6">第四步，技质部审批情况：</Text>
              {  ((curFlow && curFlow?.entId === req?.id) || req?.status!=='INIT') &&
                  <InputLine label={`技质部意见:`}>
                      <CommitInput  value={ memo || ''}  onSave={txt => setMemo( txt || undefined) }
                                    placeholder="如果拒绝或回退的，请给出理由"
                      />
                  </InputLine>
              }
              { (curFlow?.entId === req?.id && curFlow?.tdId==='request_auditor_opinion') &&
                  <>
                      <Button intent="primary" disabled={curFlow && !(curFlow?.entId === req?.id)}
                              onPress={async () => {
                                  const opndat= req?.status==='INIT' ? '' :
                                      JSON.stringify({memo,});
                                  await flowToFunc(curFlow?.utId, req?.id,3,opndat, "YES","申请报告书修订:"+user?.person?.name,
                                      null, null, 40);
                                  sessionStorage['审批单'] = null;
                                  history.push(`/zeebeTodo`);
                              }}
                      >
                      { '通过的许可修改报告' }
                      </Button>
                      {
                          (req?.status!=='INIT') &&
                          <>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify({memo,});
                                          await flowToFunc(curFlow?.utId, req?.id,3,opndat, "NO","申请报告书修订:"+user?.person?.name,
                                              auditor?.id, null, 30);
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);
                                      }}
                              >
                                  { '审批不通过' }
                              </Button>
                              <Button intent="primary" css={{marginLeft: theme.spaces.sm}}
                                      disabled={curFlow && !(curFlow?.entId === req?.id)}
                                      onPress={async () => {
                                          const opndat=JSON.stringify({memo,});
                                          await flowToFunc(curFlow?.utId, req?.id,3,opndat, "BACK","申请报告书修订:"+user?.person?.name,
                                              auditor?.id, null, 30);
                                          sessionStorage['审批单'] = null;
                                          history.push(`/zeebeTodo`);
                                      }}
                              >
                                  { '退回' }
                              </Button>
                          </>
                      }
                  </>
              }


            { (curFlow?.entId === req?.id && (curFlow?.tdId==='request_deny' || curFlow?.tdId==='request_finish')) &&
                <>
              <Button intent="primary" disabled={curFlow && !(curFlow?.entId === req?.id)}
                      onPress={async () => {
                          await flowToFunc(curFlow?.utId, req?.id,1,'', "YES");
                          sessionStorage['审批单'] = null;
                          history.push(`/zeebeTodo`);
                      }}
              >
                {'知道了'}
              </Button>
                </>
            }
              <Text>附加说明：</Text>
              <InputLine  label='本申请单链接：' >
                  <div>
                      <SuffixInput id="diame"  readOnly  onSave={txt=> 0}
                                   type="text"  value={floUrl || ""}>
                          <IconButton
                              variant="ghost"
                              icon={isCopied ? <IconZapOff /> : <IconCheckSquare />}
                              label="搜索吧"
                              onClick={async (e) => {
                                  setCopied();
                              } }
                          />
                      </SuffixInput>
                      <Text>点复制后再到报告书修订执行申请单去黏贴给申请报告书修订申请单输入框</Text>
                  </div>
              </InputLine>
          </Container>
        </div>
      </div>

    </div>
  );
};


